package com.health.work.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.health.work.R;
import com.health.work.model.AddressBean;
import com.health.work.model.DoctorExpert;
import com.health.work.model.QuestionBean;
import com.health.work.parse.AddressParse;
import com.health.work.parse.TypeParse;
import com.health.work.utils.AsyncImageLoader;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UserInfoUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 我要提问页面
 * 
 * @author star
 * 
 */
public class AskActivity extends Activity {

	private Button back;
	private Button submit;
	private TextView tjjl;
	private Button problemList;
	private EditText description;
	private EditText name;
	private final static int SUCCESSQ = -1;
	private final static int SUCCESS = 0;
	private final static int FAILE = 1;
	private final static int ERROR = 2;
	private String countyArea;
	private String township;
	private String professionalCategoryId = "1";
	private String nameConten;
	private String isExpert = "0";
	private String desContent;
	private String role;
	private Thread thread;
	private ListView docListView;
	private String mobilePhoneNum;
	private String docPhoneNum;

	public static ArrayList<DoctorExpert> doctorExpertsList;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESSQ:
				Toast.makeText(AskActivity.this, "恭喜你，提问成功", Toast.LENGTH_SHORT)
						.show();

				Intent intent = new Intent(AskActivity.this,
						ProblemsListActivity.class);
				startActivity(intent);

				break;
			case SUCCESS:
				docListAdapter adapter = new docListAdapter(AskActivity.this);
				docListView.setAdapter(adapter);
				break;
			case FAILE:
				TipsUtil.showAlert(AskActivity.this, null, "数据请求失败！");
				break;
			case ERROR:
				TipsUtil.showAlert(AskActivity.this, null, "未知错误！");
				break;
			default:
				break;
			}

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ask_layout);
		mobilePhoneNum = UserInfoUtils.getUserProperty(this,
				HEALTHPASSPORT.MOBILEPHONE);
		initPages();
		
		getData();
	}

	private void initPages() {

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			isExpert = (String) bundle.getString("isExpert");
		}
		back = (Button) findViewById(R.id.btnBack);
		submit = (Button) findViewById(R.id.submit);
		problemList = (Button) findViewById(R.id.problemlist);
		description = (EditText) findViewById(R.id.bingqing);
		tjjl = (TextView) findViewById(R.id.btnShare);
		tjjl.setOnClickListener(onClickListener);
		docListView = (ListView) findViewById(R.id.doctorlist);
		back.setOnClickListener(onClickListener);
		submit.setOnClickListener(onClickListener);
		problemList.setOnClickListener(onClickListener);
		request("0", 1);// 首次请求地址相关信息
		docListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String docName = doctorExpertsList.get(arg2).Name;
				String phoneNum = doctorExpertsList.get(arg2).MobilePhone;
				int praise = doctorExpertsList.get(arg2).Praise;
				String promiss = doctorExpertsList.get(arg2).Promise;
				String message = "姓名：" + docName + "\n手机：" + phoneNum + "\n好评："+praise
						+ "\n擅长：" + promiss;
				TipsUtil.showAlert(AskActivity.this, "医生档案", message);
			}
		});
		docListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				return false;
			}
		});
	}

	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent;
			switch (v.getId()) {
			case R.id.btnBack:
				finish();
				break;
			case R.id.submit:
				submit();
				break;
			case R.id.problemlist:
				intent = new Intent(AskActivity.this,
						ProblemsListActivity.class);
				startActivity(intent);
				break;
			case R.id.btnShare:
				intent = new Intent(AskActivity.this,
						HealthArchivesActivity.class);
				startActivity(intent);
			default:
				break;
			}
		}

	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 初始化请求参数
	 */
	private void setData() {

		desContent = description.getText().toString();

	}

	/**
	 * 请求网络数据
	 */
	private void getData() {
	
		thread = new Thread(new Runnable() {
			/**
			 * isExpert ,"true"表示专家，"false"表示普通医生 0 false 1 true
			 */
			@Override
			public void run() {
				new RequestParamtersUtil().SelectHealthyCare(province, city,
						countyArea, township, professionalCategoryId,
						nameConten, isExpert, new DefaultJSONData() {

							@Override
							public void parse(String result)
									throws JSONException {
								Log.e("SelectHealthyCareString", result);
							}

							@Override
							public void parse(JSONObject object)
									throws JSONException {
								Log.e("SelectHealthyCareobject",
										object.toString());
							}

							@Override
							public void parse(JSONArray array)
									throws JSONException {
								Log.e("SelectHealthyCareArray",
										array.toString());
								if (array != null && array.length() > 0) {
									doctorExpertsList = new ArrayList<DoctorExpert>();
									for (int i = 0; i < array.length(); i++) {
										DoctorExpert bean = new DoctorExpert();
										bean.Medium = array.getJSONObject(i)
												.getInt("Medium");
										bean.CertificateTypeId = array
												.getJSONObject(i).getInt(
														"CertificateTypeId");
										bean.Photos = array.getJSONObject(i)
												.getString("Photos");
										bean.City = array.getJSONObject(i)
												.getInt("City");
										bean.Commission = array
												.getJSONObject(i).getString(
														"Commission");
										bean.CountyArea = array
												.getJSONObject(i).getInt(
														"CountyArea");
										bean.Difference = array
												.getJSONObject(i).getInt(
														"Difference");
										bean.ExpertReason = array
												.getJSONObject(i).getString(
														"ExpertReason");
										bean.ExpertReview = array
												.getJSONObject(i).getBoolean(
														"ExpertReview");
										bean.Id = array.getJSONObject(i)
												.getInt("Id");
										bean.IDNumber = array.getJSONObject(i)
												.getString("IDNumber");
										bean.Integral = array.getJSONObject(i)
												.getInt("Integral");
										bean.Introduce = array.getJSONObject(i)
												.getString("Introduce");
										bean.MembershipType = array
												.getJSONObject(i).getString(
														"MembershipType");
										bean.MobilePhone = array.getJSONObject(
												i).getString("MobilePhone");
										bean.Name = array.getJSONObject(i)
												.getString("Name");
										bean.PassWord = array.getJSONObject(i)
												.getString("PassWord");
										bean.PersonalPhotos = array
												.getJSONObject(i).getString(
														"PersonalPhotos");
										bean.Praise = array.getJSONObject(i)
												.getInt("Praise");
										bean.ProfessionalCategoryId = array
												.getJSONObject(i)
												.getInt("ProfessionalCategoryId");
										bean.Promise = array.getJSONObject(i)
												.getString("Promise");
										bean.Province = array.getJSONObject(i)
												.getInt("Province");
										bean.Remark = array.getJSONObject(i)
												.getString("Remark");
										bean.Sex = array.getJSONObject(i)
												.getString("Sex");
										bean.Township = array.getJSONObject(i)
												.getInt("Township");
										doctorExpertsList.add(bean);
										if (array.toString() != null) {
											handler.sendEmptyMessage(SUCCESS);
										}
									}
								}
							}
						});
			}
		});
		thread.start();
	}

	/**
	 * 提交问题
	 */
	private void submit() {
		setData();
		thread = new Thread(new Runnable() {
			/**
			 * isExpert ,"true"表示专家，"false"表示普通医生 0 false 1 true
			 */
			
			@Override
			public void run() {
				Log.e(mobilePhoneNum, mobilePhoneNum+"");
				Log.e(desContent, desContent+"");
				Log.e(docPhoneNum, docPhoneNum+"");
				Log.e(professionalCategoryId, professionalCategoryId+"");
				new RequestParamtersUtil().Questions(mobilePhoneNum,
						desContent, "会员", "1", docPhoneNum,
						professionalCategoryId, new DefaultJSONData() {

					
							@Override
							public void parse(String result)
									throws JSONException {
								// TODO Auto-generated method stub
								Log.w("Questions", result);
							}

							@Override
							public void parse(JSONObject object)
									throws JSONException {
								// TODO Auto-generated method stub
								Log.e("Questionsob", object.toString());
								if (object.toString() != null) {
									handler.sendEmptyMessage(SUCCESSQ);
								} else {
									handler.sendEmptyMessage(FAILE);
								}
							}

							@Override
							public void parse(JSONArray array)
									throws JSONException {
								// TODO Auto-generated method stub
								Log.e("Questionsarr", array.toString());
							}
						});
			}
		});
		thread.start();
	}

	// 地址 及其他相关spinner
	private Spinner spinner1;
	private Spinner spinner2;
	private Spinner spinner3;
	private Spinner spinner4;
	private List<String> spinnerList1;
	private List<String> spinnerList2;
	private List<String> spinnerList3;
	private List<String> spinnerList4;
	private ArrayList<AddressBean> provinceList;
	private ArrayList<AddressBean> cityList;
	private ArrayList<AddressBean> areaList;
	private ArrayList<AddressBean> roadList;
	protected String province;
	protected String city;
	protected String area;
	protected String road;
	protected AddressParse parse;

	protected TypeParse typeParse;
	private Spinner spinner_major;
	protected ProgressDialog dialog;

	private void spinnerother() {// 其它的类别
		if (typeParse == null) {
			return;
		}

		spinner_major = (Spinner) this.findViewById(R.id.spinner_major_kink);
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,
				typeParse.nameListProfessionalCategory);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_major.setAdapter(adapter2);
		spinner_major
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int pos, long arg3) {
						professionalCategoryId = typeParse.typeListProfessionalCategory
								.get(pos).TypeId;
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						professionalCategoryId = typeParse.typeListProfessionalCategory
								.get(0).TypeId;
					}
				});
	}

	private void spinnerRelation1() {// 省
		if (spinnerList1 == null) {
			return;
		}
		spinner1 = (Spinner) this.findViewById(R.id.spinner1);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList1);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner1.setAdapter(adapter);
		spinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(provinceList.get(pos).provinceId, 2);
				province = provinceList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				province = provinceList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation2() {// 市
		if (spinnerList2 == null) {
			return;
		}
		spinner2 = (Spinner) this.findViewById(R.id.spinner2);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList2);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner2.setAdapter(adapter);
		spinner2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(cityList.get(pos).provinceId, 3);
				city = cityList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				city = cityList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation3() {// 区
		if (spinnerList3 == null) {
			return;
		}
		spinner3 = (Spinner) this.findViewById(R.id.spinner3);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList3);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner3.setAdapter(adapter);
		spinner3.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				request(areaList.get(pos).provinceId, 4);
				countyArea = areaList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				countyArea = areaList.get(0).provinceId;
			}
		});
	}

	private void spinnerRelation4() {// 其它
		if (spinnerList4 == null) {
			return;
		}
		spinner4 = (Spinner) this.findViewById(R.id.spinner4);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerList4);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner4.setAdapter(adapter);
		spinner4.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				township = roadList.get(pos).provinceId;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				township = roadList.get(0).provinceId;
			}
		});
	}

	protected void request(final String provinceId, final int i) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				if (dialog != null) {

				} else {
					dialog = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog.setCancelable(true);
				}
				if (typeParse == null) {
					typeParse = new TypeParse();
				}

				parse = new AddressParse();
			}

			@Override
			protected Void doInBackground(Void... params) {
				new RequestParamtersUtil().GetByUpId(provinceId, parse);
				if (typeParse.typeListCertificateType != null) {

				} else {
					new RequestParamtersUtil().GetType(typeParse);
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				if (spinner_major == null) {
					spinnerother();
				}

				if (i == 1) {
					provinceList = parse.addressList;
					spinnerList1 = parse.nameList;
					spinnerRelation1();
				} else if (i == 2) {
					cityList = parse.addressList;
					spinnerList2 = parse.nameList;
					spinnerRelation2();
				} else if (i == 3) {
					areaList = parse.addressList;
					spinnerList3 = parse.nameList;
					spinnerRelation3();
				} else if (i == 4) {
					roadList = parse.addressList;
					spinnerList4 = parse.nameList;
					spinnerRelation4();
					dialog.dismiss();
					dialog = null;
				}
			}
		};
		asyncLoad.execute(null);
	}

	private class docListAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private AsyncImageLoader asyncImageLoader;
		Activity context;

		public docListAdapter(Context context) {
			this.context = (Activity) context;
			asyncImageLoader = new AsyncImageLoader();
			inflater = this.context.getLayoutInflater();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return doctorExpertsList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return doctorExpertsList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder viewHodler;
			if (convertView == null) {
				viewHodler = new ViewHolder();
				convertView = inflater.inflate(R.layout.doctor_list_item,
						parent, false);
				viewHodler.headImageView = (ImageView) convertView
						.findViewById(R.id.touxiang);
				viewHodler.nameTextView = (TextView) convertView
						.findViewById(R.id.name);
				viewHodler.checkBox = (CheckBox) convertView
						.findViewById(R.id.isCheckBox);
				convertView.setTag(viewHodler);
			} else {
				viewHodler = (ViewHolder) convertView.getTag();
			}
			final DoctorExpert bean = doctorExpertsList.get(position);
			viewHodler.checkBox
					.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							// TODO Auto-generated method stub
							if (isChecked) {
								docPhoneNum = bean.MobilePhone;
							} else {

							}
						}
					});

			if (bean.Name != null) {
				viewHodler.nameTextView.setText(bean.Name);
			}

			if (bean.PersonalPhotos != null) {
				Drawable drawable = asyncImageLoader
						.loadImageFromUrl(bean.PersonalPhotos);
				if (drawable != null) {
					viewHodler.headImageView.setImageDrawable(drawable);
				} else {
					viewHodler.headImageView
							.setImageResource(R.drawable.head_scu);
				}
			}
			convertView.setTag(viewHodler);
			return convertView;
		}

	}

	class ViewHolder {
		public ImageView headImageView;
		public TextView nameTextView;
		public CheckBox checkBox;
	}
}
